package com.ywb.ex12;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

/**
 * @Author ywb
 */
public class Task01 extends JFrame {
    private JTree tree;
    public static void main(String args[]) {
        Task01 frame = new Task01();
        frame.setVisible(true);
    }
    public Task01() {
        super();
        setTitle("处理选中节点事件");
        setBounds(100, 100, 500, 375);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("本地磁 盘(E:)");
                DefaultMutableTreeNode nodeA = new DefaultMutableTreeNode("图片 ");
                root.add(nodeA);// 将一级子结点添加到跟结点
        nodeA.add(new DefaultMutableTreeNode("集美——园博园旅游"));
        DefaultMutableTreeNode nodeAB = new DefaultMutableTreeNode("鼓 浪屿——厦门旅游");
        nodeA.add(nodeAB);// 将二级子节点添加到一级子节点
        nodeAB.add(new DefaultMutableTreeNode("大浪淘沙.GIF", false));
        nodeAB.add(new DefaultMutableTreeNode("辽阔的大海.JPG",
                false));// 向二级子节点添加叶子节点
        root.add(new DefaultMutableTreeNode("音乐"));
        DefaultTreeModel treeModel = new DefaultTreeModel(root, true);
                tree = new JTree(treeModel);// 通过树模型创建树
        TreeSelectionModel treeSelectionModel =
                tree.getSelectionModel();// 获得树的选择模型
        treeSelectionModel
                .setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
        tree.addTreeSelectionListener((e) -> {
                if (!tree.isSelectionEmpty()) {
                    TreePath[] selectionPaths = tree.getSelectionPaths();
                    for (int i = 0; i < selectionPaths.length; i++) {
                        TreePath treePath = selectionPaths[i];// 获得被选中节点的路径
                        Object[] path = treePath.getPath();// 以Object数组的形式返回该路径中所有节点的对象
                        for (int j = 0; j < path.length; j++) {
                            DefaultMutableTreeNode node =
                                    (DefaultMutableTreeNode) path[j];// 获得节点
                            System.out.print(node.getUserObject()
                                    + (j == (path.length - 1) ? "" :
                                    "-->"));// 输出节点标签
                        }
                        System.out.println();
                    }
                    System.out.println();
                }
        });
        getContentPane().add(tree, BorderLayout.CENTER);
    }
}
